---
title: 'Dynamic Documents in R: R Markdown'
author: "Gina La Hera Fuentes"
date: "9/10/2021"
output:
  word_document: default
  pdf_document: default
  html_document:
    df_print: paged
    site: bookdown::bookdown_site
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## Installing and Loading 
To use R Markdown, you need R and RStudio installed.

1. Download and install [R](https://cran.rstudio.com/)
2. Download and install [RStudio](https://www.rstudio.com/products/rstudio/download/)

Once you've got **RStudio open**, then 

3. Install the R Markdown package by typing `install.packages("rmarkdown")` into the console
4. Open a new .Rmd document [File > New File > R Markdown ...]


## R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.

When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

```{r cars}
summary(cars)
mean(cars$speed)
```

## Basic Options

Within the R code cunks, you can se the following options:

- `echo=FALSE`---prevents R source code from displaying
- `eval=FALSE`---prevents Knitr from evaluating the R code
- `results='hide'`---hides the results of the code 
- `include=FALSE`---Knitr will run the code but not include in the final doc
- `warning=FALSE`---turns off warnings
- `message=FALSE`---turns off messages

# Introduction to Markdown (heading 1) 

## Markdown (heading 2)
  
Writing with __markdown__ syntax allows you to add text and graphs to your codebook and export it to an editable document format. I will demonstrate the process by using an _open source_ dataset.

### Get started with Markdown (heading 3)
We will work with the dataset and include different tables and graphs in our report. Additionally different alternatives of text can be included and also equations.
			 
#### Smaller bolding (heading 4)

We can use _italics_, **bold text**.
Make a list of items:

 - Item 1
 - Item 2
 - Item 3….

Or include numeric lists:

 1. Item 1
 2. Item 2
 3. Item 3….

You can include different links to your document. For this workshop, a useful document that you can review is the markdown [cheatsheet](https://www.rstudio.com/wp-content/uploads/2015/02/rmarkdown-cheatsheet.pdf).
			 
## Adding equations
Let's try and add an equation:  
			 $y_i=\alpha+\beta_1*X_i$

Then, let's load our packages:

```{r, echo=TRUE, message=FALSE}
need <- c("knitr","foreign","readstata13", "ggplot2", "stargazer", "coefplot", "doBy", "kableExtra", "dplyr") # list packages you need
have <- need %in% rownames(installed.packages()) # see which are already
if(any(!have)) install.packages(need[!have]) # installs the missing ones 
invisible(lapply(need, library, character.only=T)) # then loads them all
options(knit.r.table.format = "markdown")

```

# Load your data

```{r data, include=FALSE}
setwd("~/Documents/Workshop/")
data <- read.dta13("AHE_2ed_Ch_3.dta")
data <- read.dta13("~/Documents/Workshop/AHE_2ed_Ch_3.dta")
# load with package foreign
#df <- read_dta("name_doc.dta")

```

# Descriptive tables

Generate a descriptive table by injury for females and individuals with private insurance.
```{r table2, echo = FALSE}
data$injury2<-""
data$injury2[0==data$injury] <- "No"
data$injury2[1==data$injury] <- "Yes"

data_female<-summaryBy(female+private ~ injury2, FUN=c(sum), data=data)

col_order <- c("injury2", "female.sum", "private.sum")

table1 <- data_female[, col_order]

colnames(table1) <- c("Injury","Female", "Private")

knitr::kable(table1, format="markdown", caption = "Descriptives table")
```

```{r, echo = TRUE }
ggplot(data, aes(x=income, y=totexp, size=educyr)) + geom_point(aes(colour=factor(female)), alpha=I(0.5), size=1) + scale_x_continuous( name="Expediture")+ scale_y_continuous(name="Income") +theme_bw()+ scale_color_brewer( name="Sex", palette = c("Paired"))

```


# LaTeX
## Descriptive table
```{r descriptives, include = FALSE, results='asis'}
# note: option 'results = 'asis'' will generate formatted table;
# this is because 'asis' will cause chunk to process the latex formatting of stargazer command below, rather than having tex code processed further by knitr
#summary(data)
#summary(data$income)
#Hmisc::describe(data)
# or describe from package psych
#psych::describe(data)

stargazer(data, header=FALSE, summary=TRUE)
```

## Regression

Let's include a regression model.

We need to call the command lm(), which stands for linear model. Within the command we first place the dependent variable _totexp_. Next, we separate the dependent variable from the independents with the `~` symbol and we type the independent variable(s) separated by the `+` sign; in this case, only _income_, _female_, _suppins_, _phylim_, _actlim_ and _totchr_. 
Finally, define the dataset source; in this case, _data_.

We need to store the results in an object, so we can use them in post-estimations. To do that, run the same coding line, but assign it to a new object. Here, we call new object _m1_ (model 1) and _m2_ (model 2). Results are stored, but you cannot see them. To view the results, we must call or manipulate the _m1_ object (or _m2_).

```{r regression, include=FALSE}
lm(totexp ~ income + female + suppins + phylim + actlim + totchr, data = data)            # Screen the results, but not saved as an object.
m1 = lm(totexp ~ income + female + suppins + phylim + actlim + totchr, data = data)   # Save the regression model as an object.
# summary(m1)
#confint(m1)                                         # Screen the confidence interval
#coefplot(m1, predictors=c("athletes", "GDP"))          # dotplot of coefficients
# Take some time to explore the features of this object
#str(m1)
#class(m1)
#names(m1)

m2 = lm(totexp ~ income + female + suppins + phylim + actlim, data = data)   # Create a new "lm" model
#summary(m2)
#confint(m2)                                 # Confidence interval at the 95% (default)
#confint(m2,level=0.90)                      # Confidence interval at the 90%
#coefplot(m2, predictors=c("temp", "athletes", "GDP"))          # dotplot of coefficients


# Plot with confidence intervals
## Remember that option "se=FALSE"? Just delete it.
#ggplot(data.df, aes(x=athletes, y=medals)) +
#  geom_point(color="blue") +                           # Scatter
#  geom_smooth(method=lm)                   # Here I took out se=FALSE
```

We include the results in different formats (table and graph).

Including the table
```{r regressionout, include=TRUE, results='asis', warning=FALSE}
stargazer(m1, m2, header=TRUE) # type latex is default, but specified here for clarity
```

Including the graph
```{r regression-graph, include=TRUE, warning=FALSE}
coefplot(m1, predictors=c("income", "female", "suppins", "phylim", "actlim", "totchr"), title = "Coefficient Plot 1")
coefplot(m2, predictors=c("income", "female", "suppins", "phylim", "actlim"), title= "Coefficient Plot 2")
```
